package com.web.utils;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadMXBean;
 
public  class getCpuUse {
 
    private static getCpuUse instance = new getCpuUse();
 
    private static OperatingSystemMXBean osMxBean;
    private static ThreadMXBean threadBean;
    private static long preTime = System.nanoTime();
    private static long preUsedTime = 0;
 
    private getCpuUse() {
        osMxBean = ManagementFactory.getOperatingSystemMXBean();
        threadBean = ManagementFactory.getThreadMXBean();
    }
 
    public static getCpuUse getInstance() {
        return instance;
    }
 
    public static double getProcessCpu() {
        long totalTime = 0;
        for (long id : threadBean.getAllThreadIds()) {
            totalTime += threadBean.getThreadCpuTime(id);
        }
        long curtime = System.nanoTime();
        long usedTime = totalTime - preUsedTime;
        long totalPassedTime = curtime - preTime;
        preTime = curtime;
        preUsedTime = totalTime;
        return (((double) usedTime) / totalPassedTime / osMxBean.getAvailableProcessors()) * 100;
    }
}